package com.agile.leetcode.tomcat.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

/**
 * 封装nio得response请求
 *
 * @Author KD
 * @Date 2021/2/7 11:40
 */
public class MyNioResponse {
    /**
     * 将选择器组合进入
     */
    private SelectionKey selectionKey;

    public MyNioResponse(SelectionKey selectionKey) {
        this.selectionKey = selectionKey;
    }

    public void write(String content) {
        StringBuilder builder = new StringBuilder();
        builder.append("HTTP/1.1 200 OK\n")
                .append("Content-Type: text/html\n")
                .append("\r\n")
                .append("<html><body>")
                .append(content)
                .append("</body></html>");
        // 包装
        ByteBuffer buffer = ByteBuffer.wrap(builder.toString().getBytes());
        // 拿到通道
        SocketChannel channel = (SocketChannel) selectionKey.channel();
        // 写回页面
        try {
            int write = channel.write(buffer);
            if (write == -1) {
                selectionKey.cancel();
            }
            // 必须释放通道，不然会阻塞页面
            channel.close();
            selectionKey.cancel();
        } catch (IOException e) {

            e.printStackTrace();
        }
    }
}
